package cn.marinda.runnable;

import cn.marinda.entity.ServerProcess;
import lombok.Data;

import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.TimerTask;

/**
 * 服务器控制台运行线程
 *
 * @author admin
 * @date 2022/07/12
 */
@Data
public class ServerConsoleRunnable extends TimerTask {
    private ServerProcess process;
    private JTextArea textArea;

    /**
     * 服务器控制台可运行
     */
    public ServerConsoleRunnable(){

    }

    /**
     * 服务器控制台可运行
     *
     * @param process  过程
     * @param textArea 文本区域
     */
    public ServerConsoleRunnable(ServerProcess process, JTextArea textArea){
        this.process = process;
        this.textArea = textArea;
    }

    @Override
    public void run() {
            try{
                    if(process.getProcess() == null){
                        return;
                    }
                    if(process.getProcess().getInputStream() != null){
                        InputStream inputStream = process.getProcess().getInputStream();
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                        int len = 0;
                        byte[] str = new byte[bufferedInputStream.available()];
                        while((len = bufferedInputStream.read(str)) != -1){
                            String text = new String(str);
                            textArea.append(text);
                        }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

    }
}
